﻿Shader "Custom/TestShader10"
{
    Properties
    {
        _Color("Color", color) = (1,1,1,1)
        _Scale("Scale", range(0,1)) = 1
        _Cube("Cube", Cube) = "_Skybox"{}
        _RefractRatio("RefractRatio", range(0,1)) = 1
        _FresnelScale("FresnelScale", range(0,1)) = 1
    }
        SubShader
    {
        Pass
        {
            Tags {"LightMode" = "ForwardBase"}
            CGPROGRAM
            #pragma multi_compile_fwdbase
            #pragma vertex vert
            #pragma fragment frag
            #include "Lighting.cginc"
            #include "AutoLight.cginc"

            fixed4 _Color;
            float _Scale;
            samplerCUBE _Cube;
            float _RefractRatio;
            float _FresnelScale;
            struct a2v
            {
                float4 vertex : POSITION;
                float3 normal : NORMAL;
            };

            struct v2f
            {
                float4 pos : SV_POSITION;
                float3 worldNormal : TEXCOORD0;
                float3 worldReflect : TEXCOORD1;
                float3 worldPos : TEXCOORD2;
                SHADOW_COORDS(3)
            };

            v2f vert(a2v v)
            {
                v2f o; 
                o.pos = UnityObjectToClipPos(v.vertex);
                o.worldNormal = UnityObjectToWorldNormal(v.normal);
                o.worldPos = mul(unity_ObjectToWorld, v.vertex);

                float3 worldViewDir = UnityWorldSpaceViewDir(v.vertex);

                o.worldReflect = reflect(-worldViewDir, o.worldNormal);
                //o.worldReflect = refract(-worldViewDir, o.worldNormal, _RefractRatio);
                TRANSFER_SHADOW(o)
                return o;
            }

            fixed4 frag(v2f i) : SV_Target
            {
                fixed3 ambient = UNITY_LIGHTMODEL_AMBIENT.rgb;
                fixed3 worldNormal = normalize(i.worldNormal);
                fixed3 viewDir = normalize(UnityWorldSpaceViewDir(i.worldPos));
                fixed3 lightDir = normalize(UnityWorldSpaceLightDir(i.worldPos));
                fixed3 diffuse = _LightColor0.rgb * saturate(dot(worldNormal, lightDir));

                fixed3 reflectColor = texCUBE(_Cube, i.worldReflect).rgb;

                fixed fresnel = _FresnelScale + (1 - _FresnelScale) * pow(1 - dot(worldNormal, viewDir), 5);
                UNITY_LIGHT_ATTENUATION(atten, i, i.worldPos);
                return fixed4(ambient + lerp(diffuse, reflectColor, saturate(fresnel))  * atten, 1);
            }

            ENDCG
        }
    }
    Fallback "Specular"
}